package cn.stronglink.assetmanage.business.search;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.search.presenter.AssisChangePresenter;
import cn.stronglink.assetmanage.business.search.presenter.IAssetDetailView;
import cn.stronglink.assetmanage.business.search.view.ISearchView;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.InventoryDataUtil;
import cn.stronglink.assetmanage.utils.dao.PatrolDataUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;

public class SearchDetailsActivity extends BaseActivity implements View.OnClickListener, IAssetDetailView,
        IScanerListener, View.OnTouchListener {
    private SearchAsset searchAsset;
    private String roomId = "", typeId = "", brandId = "", modelId = "", userId = "";
    private Spinner sp_search_asset_class, sp_search_location, sp_search_brand_name,
            sp_search_model_name;
    private EditText tv_sn, tv_check_asset_no, ed_search_asset_name, ed_search_supplier, tv_rfid;
    private ImageView img_btn_cancel, img_search_camera, img_search_album, img_scanning;
    private Button btn_cancel, btn_save;
    private List<Type> typeList;
    private List<Brand> brandList;
    private List<Model> modelList;
    private List<Room> roomList;
    private ArrayAdapter<Model> modelArrayAdapter;
    private ArrayAdapter<Type> typeArrayAdapter;
    private ArrayAdapter<Brand> brandArrayAdapter;
    private ArrayAdapter<Room> roomArrayAdapter;
    private Bitmap bitmap;
    private Dialog mDialog;
    private TimerInfraraedScaner scaner;
    private TextView textView;
    private AssisChangePresenter assisChangePresenter;
    private int PICTURE_URL = 1000;
    private int PICTURE_LOCAL = 1001;
    private static final String TAG = "SearchDetailsActivity";
    private String btimapPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_search_details);
        try {
            initView();
            initData();
            initListener();
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }


    private void initListener() {
        tv_check_asset_no.setOnTouchListener(this);
        tv_sn.setOnTouchListener(this);
        tv_rfid.setOnTouchListener(this);
        btn_save.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        img_search_camera.setOnClickListener(this);
        img_search_album.setOnClickListener(this);

    }

    private void initView() {
        ed_search_asset_name = findViewById(R.id.ed_search_asset_name);
        sp_search_asset_class = findViewById(R.id.sp_search_asset_class);
        sp_search_location = findViewById(R.id.sp_search_location);
        sp_search_brand_name = findViewById(R.id.sp_search_brand_name);
        sp_search_model_name = findViewById(R.id.sp_search_model_name);
        ed_search_supplier = findViewById(R.id.ed_search_supplier);
        tv_check_asset_no = findViewById(R.id.tv_check_asset_no);
        tv_sn = findViewById(R.id.tv_sn);
        tv_rfid = findViewById(R.id.tv_rfid);
        img_btn_cancel = findViewById(R.id.img_btn_cancel);
        img_search_camera = findViewById(R.id.img_search_camera);
        img_search_album = findViewById(R.id.img_search_album);
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_save = findViewById(R.id.btn_save);
        scaner = new TimerInfraraedScaner(this);
        scaner.setScanerListener(this);
    }

    private void initData() {
        assisChangePresenter = new AssisChangePresenter(this, this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String assetId_ = bundle.getString(Constants.CHECK_IN_DETAIL_NO);
            searchAsset = assisChangePresenter.getAssetDetail(assetId_);
        }
        if (searchAsset == null) {
            searchAsset = new SearchAsset();
        }
        typeList = assisChangePresenter.getTypeList();
        brandList = assisChangePresenter.getBrandList();
        modelList = assisChangePresenter.getModelList();
        roomList = assisChangePresenter.getRoomList();
        typeArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, typeList);
        brandArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, brandList);
        modelArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, modelList);
        roomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, roomList);
        sp_search_asset_class.setAdapter(typeArrayAdapter);
        sp_search_asset_class.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Type type = (Type) sp_search_asset_class.getSelectedItem();
                typeId = type.getId_();
                assisChangePresenter.queryModelByBrandAndType();
                if (position != 0) {
                    searchAsset.setTypeId_(typeId);
                    searchAsset.setTypeName(type.getName());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_search_model_name.setAdapter(modelArrayAdapter);
        sp_search_model_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Model model = (Model) sp_search_model_name.getSelectedItem();
                modelId = model.getId_();
                if (position != 0) {
                    searchAsset.setModelId_(modelId);
                    searchAsset.setModelName(model.getName());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_search_brand_name.setAdapter(brandArrayAdapter);
        sp_search_brand_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Brand brand = (Brand) sp_search_brand_name.getSelectedItem();
                brandId = brand.getId_();
                assisChangePresenter.queryModelByBrandAndType();
                if (position != 0) {
                    searchAsset.setBrandId_(brandId);
                    searchAsset.setBrandName(brand.getName());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_search_location.setAdapter(roomArrayAdapter);
        sp_search_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) sp_search_location.getSelectedItem();
                roomId = room.getId_();
                if (position != 0) {
                    searchAsset.setRoomId_(roomId);
                    searchAsset.setRoomName(room.getName());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (searchAsset != null) {
            if (searchAsset.getAssetName() != null) {
                ed_search_asset_name.setText(searchAsset.getAssetName());
            }
            if (searchAsset.getTypeName() != null) {
                DetailsUtils.setSpinnerItemSelectedByValue(sp_search_asset_class, searchAsset.getTypeName());
            }
            if (searchAsset.getModelName() != null) {
                DetailsUtils.setSpinnerItemSelectedByValue(sp_search_model_name, searchAsset.getModelName());
            }
            if (searchAsset.getBrandName() != null) {
                DetailsUtils.setSpinnerItemSelectedByValue(sp_search_brand_name, searchAsset.getBrandName());
            }
            if (searchAsset.getRoomName() != null) {
                DetailsUtils.setSpinnerItemSelectedByValue(sp_search_location, searchAsset.getRoomName());
            }
            if (searchAsset.getAssetNo() != null) {
                tv_check_asset_no.setText(searchAsset.getAssetNo());
            }
            if (searchAsset.getSerialNo() != null) {
                tv_sn.setText(searchAsset.getSerialNo());
            }
            if (searchAsset.getRfidNo() != null) {
                tv_rfid.setText(searchAsset.getRfidNo());
            }
            if (searchAsset.getPictureUri() != null) {
                btimapPath = searchAsset.getPictureUri();
                bitmap = assisChangePresenter.getBitmap(searchAsset.getPictureUri());
                if (bitmap != null) {
                    img_btn_cancel.setImageBitmap(bitmap);
                }
            }
            if (searchAsset.getSupplier() != null) {
                ed_search_supplier.setText(searchAsset.getSupplier());
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            int whichBusiness = PrefUtils.getInt(PrefUtils.WHICH_SEARCH_DETAIL, 6, this);
            setSelectPosition(whichBusiness);
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_save:
                searchAsset.setAssetNo(tv_check_asset_no.getText().toString());
                searchAsset.setSerialNo(tv_sn.getText().toString());
                searchAsset.setRfidNo(tv_rfid.getText().toString());
                searchAsset.setAssetName(ed_search_asset_name.getText().toString());
                searchAsset.setSupplier(ed_search_supplier.getText().toString());
                searchAsset.setPictureUri(btimapPath);
                SyncTypes syncType = DaoManager.getDaoSession(this).getSyncTypesDao()
                        .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
                int tp = 0;
                if (syncType != null) {
                    tp = syncType.getSyscTs();
                }

                if (tp == 1) {
                    showProgress(getString(R.string.is_upload));
                } else {
                    showProgress("正在保存图片");
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        assisChangePresenter.save(searchAsset);
                    }
                }).start();

                break;
//                调用相册
            case R.id.img_search_album:
                startActivityForPicture(PICTURE_LOCAL);
                break;
//                调用相机
            case R.id.img_search_camera:
                startActivityForPicture(PICTURE_URL);
                break;
            default:
                break;
        }
    }

    @Override
    public void onUploadSuccess(SearchAsset searchAsset) {
        assisChangePresenter.saveToLocal(searchAsset);
        ToastUtil.toastShort("资产更新成功");
        onBackPressed();
    }

    @Override
    public void onUploadFail(Exception e, final SearchAsset searchAsset) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("资产上传失败:" + e.getMessage() + "，是否保存到本地？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        assisChangePresenter.saveToLocal(searchAsset);
                    }
                });
        builder.create().show();
    }

    @Override
    public void onSaveLocalSuccess(SearchAsset searchAsset) {
        ToastUtil.toastShort("数据已保存到本地成功");
        finish();
    }

    @Override
    public void onSaveLocalFail(Exception e) {
        ToastUtil.toastShort("保存到本地失败:" + e.getMessage());
    }

    @Override
    public void showProgress(final String msg) {
        try {
            mDialog = CustomProgressDialog.createLoadingDialog(SearchDetailsActivity.this, msg);
            mDialog.setCancelable(false);
            mDialog.show();
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Override
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDialog != null) {
                    mDialog.cancel();
                }
            }
        });
    }

    @Override
    public String getTypeValue() {
        return typeId;
    }

    @Override
    public String getRoomValue() {
        return roomId;
    }

    @Override
    public String getSnValue() {
        return tv_sn.getText().toString();
    }

    @Override
    public String getRfidValue() {
        return tv_rfid.getText().toString();
    }

    @Override
    public String getBrandValue() {
        return brandId;
    }

    @Override
    public String getModelValue() {
        return modelId;
    }

    @Override
    public String getUserValue() {
        return userId;
    }

    @Override
    public Bitmap getCurrentBitmap() {
        return bitmap;
    }

    @Override
    public void onQueryModelListSuccess(List<Model> modelList) {
        modelArrayAdapter.clear();
        modelArrayAdapter.addAll(modelList);
    }

    private void startActivityForPicture(int requestCode) {
        if (requestCode == 1000) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //启动相机程序
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            startActivityForResult(intent, requestCode);
        } else {
            Intent intent = null;
            if (Build.VERSION.SDK_INT < 19) {
                intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            }
            startActivityForResult(intent, requestCode);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case 1000:
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                            if (bitmap != null) {
                                img_btn_cancel.setImageBitmap(bitmap);
                                btimapPath = ImageUtils.saveImageToLocal(bitmap);
                            } else {
                                ToastUtil.toastShort("图片损坏，不能使用");
                            }

                        }
                        break;
                    case 1001:
                        if (data != null) {
                            Uri selectedImage = data.getData();
                            String[] filePathColumns = {MediaStore.Images.Media.DATA};
                            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                            c.moveToFirst();
                            int columnIndex = c.getColumnIndex(filePathColumns[0]);
                            btimapPath = c.getString(columnIndex);
                            showImage(btimapPath);
                            c.close();
                        }
                        break;
                }

                break;
            case RESULT_CANCELED:

                break;
        }
    }

    //加载图片
    private void showImage(String imaePath) {
        if (imaePath != null) {
            Bitmap bitmap = ImageUtils.getNativeImage(imaePath);
            if (bitmap != null) {
                bitmap = ImageUtils.comp(bitmap);
                img_btn_cancel.setImageBitmap(bitmap);
            } else {
                ToastUtil.toastShort("图片损坏，不能使用");
            }
        } else {
            ToastUtil.toastShort("图片损坏，不能使用");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDialog != null && !this.isFinishing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (scaner != null) {
                scaner.setScanerListener(this);
                scaner.stop();
                scaner.destory();
            }
            if (mDialog!=null) {
                mDialog.cancel();
            }
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }


    @Override
    public void onScaning(List<String> data) {
        String value = data.get(data.size() - 1).replace("\r", "");
        textView.setText(value);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                switch (v.getId()) {
                    //                扫描资产编码
                    case R.id.tv_check_asset_no:
                        textView = tv_check_asset_no;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
//                扫描SN
                    case R.id.tv_sn:
                        textView = tv_sn;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
//                扫描RFID
                    case R.id.tv_rfid:
                        textView = tv_rfid;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
        return false;
    }
}
